package com.tianji.promotion.service.impl;

import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.domain.po.ExchangeCode;
import com.tianji.promotion.mapper.ExchangeCodeMapper;
import com.tianji.promotion.service.IExchangeCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.promotion.utils.CodeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.tianji.promotion.constants.ExchangeCodeConstants.*;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author lcm
 * @since 2023-08-01
 */
@Service
@Slf4j
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {

    private final StringRedisTemplate redisTemplate;
    private final BoundValueOperations<String, String> boundValueOps;
    ExchangeCodeServiceImpl(StringRedisTemplate redisTemplate){
        this.redisTemplate=redisTemplate;
        this.boundValueOps= redisTemplate.boundValueOps(COUPON_CODE_SERIAL_KEY);
    }

    /**
     * 异步生成兑换码
     *
     * @param coupon
     */
    @Override
    @Async("generateExchangeCodeExecutor")
    public void asyncGenerateCode(Coupon coupon) {
        //1.获取发放数量
        Integer totalNum = coupon.getTotalNum();
        //2.获取redis自增id
        Long result = boundValueOps.increment(totalNum);
        if(result == null){
            return;
        }

        int max = result.intValue();
        List<ExchangeCode> list = new ArrayList<>(totalNum);
        for (int i = max-totalNum+1; i <= max ; i++) {
            //3.生成兑换码
            String code = CodeUtil.generateCode(i, coupon.getId());
            ExchangeCode exchangeCode = new ExchangeCode();
            exchangeCode.setCode(code);
            exchangeCode.setId(i);
            exchangeCode.setExchangeTargetId(coupon.getId());
            exchangeCode.setExpiredTime(coupon.getIssueEndTime());
            list.add(exchangeCode);
        }
        //4.保存至数据库
        saveBatch(list);
//        //5.记录本次发放兑换码使用的最大自增id，下次使用时不会使用重复id
//        redisTemplate.opsForZSet().add(COUPON_RANGE_KEY, coupon.getId().toString(), max);

    }

    /**
     * 校验兑换码是否使用过
     *
     * @param serialNum
     * @param b
     * @return
     */
    @Override
    public boolean updateExchangeMark(long serialNum, boolean mark) {
        Boolean boo = redisTemplate.opsForValue().setBit(COUPON_CODE_MAP_KEY, serialNum, mark);
        return boo != null && boo;
    }
}
